package net.maku.kyy.controller;


import cn.hutool.core.util.RandomUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import net.maku.api.module.system.SmsApi;

import net.maku.framework.common.utils.PageResult;
import net.maku.framework.common.utils.Result;
import net.maku.framework.operatelog.annotations.OperateLog;
import net.maku.framework.operatelog.enums.OperateTypeEnum;
import net.maku.kyy.service.KyyUserService;
import net.maku.kyy.query.KyyUserQuery;
import net.maku.kyy.vo.CommentStatusTimeVO;
import net.maku.kyy.vo.KyyUserInfoVO;
import net.maku.kyy.vo.KyyUserPhoneVO;
import net.maku.kyy.vo.KyyUserVO;
import net.maku.tencentsms.service.TencentSmsService;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 应用用户信息表
 *
 * @author MAKU babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Slf4j
@RestController
@RequestMapping("/kyy/user")
@Tag(name="前台用户表")
@AllArgsConstructor
public class KyyUserController {
    @Autowired
    private KyyUserService kyyUserService;

    @Autowired
    private TencentSmsService smsApi;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @GetMapping("page")
    @Operation(summary = "分页")
//    @PreAuthorize("hasAuthority('sys:kyy:user')")
    public Result<PageResult<KyyUserVO>> page(@ParameterObject @Valid KyyUserQuery query){
        PageResult<KyyUserVO> page = kyyUserService.page(query);

        return Result.ok(page);
    }


    @GetMapping("{id}")
    @Operation(summary = "信息")
//    @PreAuthorize("hasAuthority('sys:kyy:user')")
    public Result<KyyUserVO> get(@PathVariable("id") Long id){
        KyyUserVO data = kyyUserService.get(id);
        return Result.ok(data);
    }

    @PostMapping
    @Operation(summary = "保存")
    @OperateLog(type = OperateTypeEnum.INSERT)
//    @PreAuthorize("hasAuthority('sys:kyy:user')")
    public Result<String> save(@RequestBody KyyUserVO vo){
        kyyUserService.save(vo);

        return Result.ok();
    }

    @PutMapping
    @Operation(summary = "修改")
    @OperateLog(type = OperateTypeEnum.UPDATE)
//    @PreAuthorize("hasAuthority('sys:kyy:user')")
    public Result<String> update(@RequestBody @Valid KyyUserVO vo){
        System.out.println("vo = " + vo);
        // 验证ID不能为空
        if(vo.getId() == null){
            return Result.error("用户ID不能为空");
        }
        kyyUserService.update(vo);

        return Result.ok();
    }

    @DeleteMapping
    @Operation(summary = "删除")
    @OperateLog(type = OperateTypeEnum.DELETE)
//    @PreAuthorize("hasAuthority('sys:kyy:user')")
    public Result<String> delete(@RequestBody List<Long> idList){
        kyyUserService.delete(idList);
        return Result.ok();
    }


    @GetMapping("export")
    @Operation(summary = "导出")
    @OperateLog(type = OperateTypeEnum.EXPORT)
//    @PreAuthorize("hasAuthority('sys:kyy:user')")
    public void export() {
        kyyUserService.export();
    }


    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/info")
    @Operation(summary = "获取用户信息")
//    @PreAuthorize("hasAuthority('sys:kyy:user')")
    public Result<KyyUserInfoVO> getUserInfo() {
        log.info("获取用户信息");
        KyyUserInfoVO kyyUserInfoVO = kyyUserService.getUserInfo();
        return Result.ok(kyyUserInfoVO);
    }

    /**
     * 禁用用户
     * @param userId
     * @return
     */
//    @PreAuthorize("hasAuthority('sys:kyy:user:ban')")
    @GetMapping("/update/status")
    public Result banUserStatus(Long userId) {
//        log.info("禁用用户");
        kyyUserService.updateUserStatus(userId);
        return Result.ok();
    }

    /**
     * 修改论坛状态
     * @param userId
     * @return
     */
//    @PreAuthorize("hasAuthority('sys:kyy:user')")
    @GetMapping("/update/forum/status")
    public Result updateForumStatus(Long userId) {
        kyyUserService.updateForumStatus(userId);
        return Result.ok();
    }

    /**
     * 修改发言权限
     */
//    @PreAuthorize("hasAuthority('sys:kyy:user')")
    @GetMapping("/update/comment/status")
    public Result updateCommentStatus(Long userId) {
        kyyUserService.updateCommentStatus(userId);
        return Result.ok();
    }

    /**
     * 封禁发言特定时间
     * @param commentStatusTimeVO
     * @return
     */
    @PostMapping("/update/comment/status/time")
    public Result updateCommentStatusTime(@RequestBody CommentStatusTimeVO commentStatusTimeVO) {
        kyyUserService.updateCommentStatusTime(commentStatusTimeVO);
        return Result.ok();
    }

    /**
     * 获取禁用所剩时间
     * @param userId
     * @return
     */
    @GetMapping("/get/silence/remaining/time")
    public Result getSilenceRemainingTime(Long userId) {
        Long time=kyyUserService.getSilenceRemainingTime(userId);
        return Result.ok(time);
    }


    /**
     * 发送更换验证码
     * @param phone 手机号
     * @return
     */
    @PostMapping("/sendcode/{phone}")
    public Result sendCode(@PathVariable("phone")String phone) {
        log.info("发送注册验证码，手机号：{}", phone);

        // 生成6位数字验证码
        String code = RandomUtil.randomNumbers(6);

        try {
            System.out.println(redisTemplate);
            redisTemplate.opsForValue().set("kyy:changephone:code:" + phone, code, 5, TimeUnit.MINUTES);
            System.out.println("Redis连接测试成功，获取的值: ");
            smsApi.sendSms(phone, new String[]{code});
        } catch (Exception e) {
            System.err.println("Redis连接失败: " + e.getMessage());
        }
        System.out.println("验证码发送成功，验证码：" + code);
        return Result.ok();
    }

    /**
     * 修改手机号
     * @param vo
     * @return
     */
    @PostMapping("/changephone")
//    @PreAuthorize("hasAuthority('sys:kyy:user')")
    public Result<String> update(@RequestBody @Valid KyyUserPhoneVO vo){
        System.out.println("vo = " + vo);

        // 验证ID不能为空
        if(vo.getUser().getId() == null){
            return Result.error("用户ID不能为空");
        }
        String code = (String) redisTemplate.opsForValue().get("kyy:changephone:code:" + vo.getUser().getMobile());
        System.out.println("kyy:changephone:code:" + vo.getUser().getMobile());
        System.out.println("code = " + code);

        if(code.equals(vo.getCode())){
            kyyUserService.update(vo.getUser());
            return Result.ok("success");

        }
        return Result.ok("fail");
    }
}